package com.example.demo4activemq

import org.springframework.boot.SpringApplication
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.autoconfigure.jms.DefaultJmsListenerContainerFactoryConfigurer
import org.springframework.context.annotation.Bean
import org.springframework.jms.annotation.EnableJms
import org.springframework.jms.config.DefaultJmsListenerContainerFactory
import org.springframework.jms.config.JmsListenerContainerFactory
import org.springframework.jms.core.JmsTemplate
import org.springframework.jms.support.converter.MappingJackson2MessageConverter
import org.springframework.jms.support.converter.MessageConverter
import org.springframework.jms.support.converter.MessageType

import javax.jms.ConnectionFactory

@EnableJms
@SpringBootApplication
class Demo4activemqApplication {

    @Bean
    JmsListenerContainerFactory<?> myFactory(ConnectionFactory connectionFactory,
                                             DefaultJmsListenerContainerFactoryConfigurer configurer) {
        DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory()
        // This provides all boot's default to this factory, including the message converter
        configurer.configure(factory, connectionFactory)
        // You could still override some of Boot's default if necessary.
        return factory
    }

    @Bean
    // Serialize message content to json using TextMessage
    MessageConverter jacksonJmsMessageConverter() {
        MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter()
        converter.setTargetType(MessageType.TEXT)
        converter.setTypeIdPropertyName("_type")
        return converter
    }

    static void main(String[] args) {
        def context = SpringApplication.run(Demo4activemqApplication, args)
        final jmsTemplate = context.getBean(JmsTemplate.class)
        Thread.start {
            def count = 0
            while (count < 100) {
                println "Sending an email message."
                jmsTemplate.convertAndSend("demo.mailbox", new Email("info@example.com", "Hello, ${new Date()}"))
                count++
                sleep 1000
            }
        }
        jmsTemplate.convertAndSend("demo.map", [aaa: "aaa", bbb: [ccc: 1]])
    }

}
